package mouvement;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;

import modele.AbsPiece;

public class GenerateurMouvement {
    private Hashtable<String, AbsPiece> tblPiece;
    
    public GenerateurMouvement() {
        tblPiece = new Hashtable<String, AbsPiece>();
    }
    
    public void addPiece(String position, AbsPiece piece) {
        tblPiece.put(position, piece);
    }
    
    public void bouge(String mouvement) {
        String cases1 = mouvement.substring(0,2);
        String cases2 = mouvement.substring(2,4);
        
        AbsPiece piece = tblPiece.get(cases1);
        piece.setPosition(cases2);
        
        tblPiece.remove(cases1);
        tblPiece.put(cases2, piece);
    }
    
    public void removePiece(String position) {
        tblPiece.remove(position);
    }
    
    public LinkedList<String> getPossibilites(int[][] grille) {
        LinkedList<String> retour = new LinkedList<String>();
        Enumeration<AbsPiece> pieces = tblPiece.elements();
        
        while(pieces.hasMoreElements()) {
            AbsPiece piece = pieces.nextElement();
            String position = piece.getPosition();
            
            int colonne = position.charAt(0) - 'A';
            int ligne = 8 - Integer.parseInt(String.valueOf(position.charAt(1)));
            
            int[][] region = new int[2][3];
            
            for(int i = 0; i < 2; i ++) {
                for(int j = 0; j < 3; j++) {
                    int colonneAct = colonne + j - 1;
                    int ligneAct = ligne + ((1-i)*-1) + i;
                    if(colonneAct >= 0 && colonneAct < 8 && ligneAct >= 0 && ligneAct < 8) {
                        region[i][j] = grille[colonneAct][ligneAct];
                    } else {
                        region[i][j] = -1;
                    }

                }
            }
            
            LinkedList<String> possiblePiece = piece.getPossibilite(region);
            retour.addAll(possiblePiece);
        }
        return retour;
        
    }
    
    public String toString() {
        Enumeration<AbsPiece> pieces = tblPiece.elements();
        String retour = "";
        while(pieces.hasMoreElements()) {
            AbsPiece piece = pieces.nextElement();
            retour += piece.toString() + '\n';
        }
        
        return retour;
    }
}
